<template>

  <div>
    <!--新增区域-->
    <div class="iRight">
      <el-button type="primary" @click="add">新增</el-button>
    </div>

    <!--搜索区域-->
    <div style="margin: 10px 0">
      <el-input v-model="search" style="width: 20%" placeholder="输入关键字搜索" clearable/>
      <el-button type="primary" style="margin-left: 5px" @click="load">查询</el-button>
    </div>


    <!--文章列表-->
    <el-table :data="tableData" border stripe style="width: 100%">
      <el-table-column property="title" label="标题" width="120px"></el-table-column>
      <el-table-column property="author" label="作者"></el-table-column>
      <el-table-column prop="time" label="创建时间"></el-table-column>
      <el-table-column label="操作">

        <template #default="scope">
          <el-button @click="details(scope.row)">详情</el-button>
          <el-button @click="handleEdit(scope.row)">编辑</el-button>
          <el-popconfirm title="确认删除吗？" hide-icon @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!--新增弹框-->
    <el-dialog v-model="dialogVisible" width="70%">

      <el-form :model="form" :label-position="labelPosition" label-width="120px">
        <el-form-item label="标题">
          <el-input v-model="form.title" style="width: 80%"></el-input>
        </el-form-item>

        <!--正文-->
        <div id="div1"></div>


      </el-form>


      <template #footer>
    <span class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </span>
      </template>
    </el-dialog>


    <!--文章正文弹窗-->
    <el-dialog v-model="vis" width="50%">
      <el-card>
        <div v-html="detail.content" style="min-height:300px">

        </div>
      </el-card>

    </el-dialog>


    <!--分页脚标-->
    <div class="iRight">
      <el-pagination
          :total="total" :current-page="currentPage"
          background layout="prev, pager, next"
          @current-change="handleCurrentChange">
      </el-pagination>
    </div>


  </div>
</template>

<script>
import request from "@/utils/request";

//引文wangEditor富文本编辑器
import E from 'wangeditor';

let editor;

export default {
  name: "Blog",
  components: {},

  data() {
    return {
      form: {},
      dialogVisible: false,
      search: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      labelPosition: 'left',
      imgURl: '',
      detail: {},
      vis: false,
    }
  },

  created() {
    this.load()
  },

  methods: {
    //文章详情
    details(row) {
      this.detail = row
      this.vis = true
    },

    //编辑
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true

      this.$nextTick(() => {
        //关联新增弹窗里的div1，new一个editor
        editor = new E('#div1')

        // 配置 server 接口地址
        editor.config.uploadImgServer = "http://" + window.server.filesUploadUrl + ":9090/files/editor/upload"
        //设置上传参数名称
        editor.config.uploadFileName = "file"

        editor.create()
        //将富文本内容展示在编辑中
        editor.text.html(row.content)
      })


    },
    //删除
    handleDelete(id) {
      console.log(id);
      request.delete("/article/" + id).then(res => {
        if (res.code === '0') {
          this.$message({
            type: "success",
            message: "删除成功"
          })
        } else {
          this.$message({
            type: "error",
            message: res.msg
          })
        }
        this.load() //删除完成之后刷新表格数据
      })
    },
    //改变当前页
    handleCurrentChange(pageNum) {
      this.currentPage = pageNum
      this.load()
    },

    //新增
    add() {
      this.dialogVisible = true
      this.form = {}

      this.$nextTick(() => {
        //关联新增弹窗里的div1，new一个editor
        editor = new E('#div1')

        // 配置 server 接口地址
        editor.config.uploadImgServer = "http://" + window.server.filesUploadUrl + ":9090/files/editor/upload"
        //设置上传参数名称
        editor.config.uploadFileName = "file"

        editor.create()
      })


    },
    //保存
    save() {
      console.log(editor.txt.html())

      this.form.content = editor.txt.html()   //获取编辑器里面的内容，再赋予到实体中


      if (this.form.id) {
        //有id则更新
        request.put("/article", this.form).then(res => {
          console.log(res)
          if (res.code === '0') {
            this.$message({
              type: "success",
              message: "更新成功"
            })
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
          this.load() //更新完成之后刷新表格数据
          this.dialogVisible = false //并且关闭弹窗
        })
      } else {
        //获取用户对象
        let userStr = sessionStorage.getItem("user") || "{}"
        let user = JSON.parse(userStr)

        //将用户名赋值给作者
        this.form.author = user.username;

        //没有id则新增
        request.post("/article", this.form).then(res => {
          console.log(res)
          if (res.code === '0') {
            this.$message({
              type: "success",
              message: "新增成功"
            })
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
          this.load() //新增完成之后刷新表格数据
          this.dialogVisible = false //并且关闭弹窗
        })
      }
    },

    //查询
    load() {
      request.get("/article", {
        params: {
          pageNum: this.currentPage,
          search: this.search,
        }
      }).then(res => {
        console.log(res)
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },

    //头像上传
    handleAvatarSuccess(res, file) {
      console.log(res);
      this.form.avatar = res.data;
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
  }
}
</script>

<style scoped>
/*.iRight {*/
/*  margin: 10px 0;*/
/*  position: absolute;*/
/*  right: 10px;*/
/*  text-align: center;*/
/*}*/

/*头像上传*/
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>